import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import axios from 'axios';
import ApiHandler from './ApiHandler';

const baseUrl = process.env.NODE_ENV === 'production' ? _ctxPath + '/rest' : '/seeyon/rest';
// 全局header
const headers = {};
if (window.CSRFTOKEN) {
	headers['X-Requested-With'] = 'XMLHttpRequest';
	headers.CSRFTOKEN = window.CSRFTOKEN;
}

const WebClient = axios.create({
	baseURL: baseUrl,
	timeout: 60000,
	withCredentials: true,
	headers
});

//配置请求拦截器
WebClient.interceptors.request.use(
	(config) => {
		/**
     * rest接口数据number as string配置
     * @type {string}
     */
		NProgress.start()
		if (config.params) {
			config.params['option.n_a_s'] = '1';
		} else {
			config.params = { 'option.n_a_s': '1' };
		}
		return config;
	},
	(error) => {
		console.error('Client Request',error);
		return error;
	},
);

//配置响应拦截器
WebClient.interceptors.response.use(
	(response) => {
		NProgress.done()
		if (response.status === 200) {
			response.data.code = Number(response.data.code);
			return response.data;
		}
		return {};
	},
	(error) => {
		NProgress.done()
		if (error.response) {
			const responseData = error.response.data;
			responseData.code = Number(responseData.code);
			const handler = ApiHandler.getHandler(responseData.code);
			if (handler !== null) {
				handler(responseData);
			}
			console.error('Server Response',responseData);
			return responseData;
		} else if (error.isAxiosError) {
			let message = error.message;
			if (message === undefined || message.includes('timeout')) {
				message = '请求超时，请检查网络连接或稍后再试！';
			}
			console.error('Axios Request',error);
			return {
				code: '-1',
				message
			};
		}
		let errorMsg = {
			code: '-1',
			message: '出现未知异常，请稍后再试！'
		};
		console.error('Unknown Response',errorMsg);
		return errorMsg;
	},
);

export default {
	/**
   * post 请求
   * @param url url
   * @param data post数据
   * @returns {*}
   */
	post: (url, data = {}) => {
		return WebClient.post(url, data);
	},
	/**
   * get请求
   * @param url   url
   * @param queryParams 请求参数
   * @returns {*}
   */
	get: (url, queryParams = {}) => {
		return WebClient.get(url, {
			params: queryParams
		});
	}
};
